<template>
  <el-form
    ref="formRef"
    :model="formData"
    :rules="rules"
    label-width="80px"
    class="user-profile-form"
  >
    <el-form-item label="账号" prop="account">
      <el-input v-model="formData.account" :disabled="!isCreate" />
    </el-form-item>
    
    <el-form-item label="姓名" prop="name">
      <el-input v-model="formData.name" />
    </el-form-item>
    
    <el-form-item label="签名" prop="signature">
      <el-input 
        v-model="formData.signature" 
        type="textarea" 
        :rows="3" 
        placeholder="请输入个人签名"
      />
    </el-form-item>
    
    <el-form-item label="头像" prop="avatar">
      <el-upload
        class="avatar-uploader"
        action=""
        :auto-upload="false"
        :show-file-list="false"
        :on-change="handleAvatarChange"
      >
        <img v-if="previewAvatarUrl || formData.avatar" :src="previewAvatarUrl || formData.avatar" class="avatar" />
        <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
      </el-upload>
      <div v-if="pendingAvatarFile" class="pending-upload-info">
        <el-tag type="info" size="small">待上传（需点击保存按钮，否则将不会保存）</el-tag>
      </div>
    </el-form-item>
    
    <!-- 创建用户时需要填写密码 -->
    <el-form-item v-if="isCreate" label="密码" prop="password">
      <el-input 
        v-model="formData.password" 
        type="password" 
        show-password
        placeholder="请输入密码"
      />
    </el-form-item>
    
    <!-- 编辑用户时，只有在需要修改密码时才显示密码输入框 -->
    <template v-else>
      <el-form-item label="修改密码">
        <el-switch 
          v-model="changePassword" 
          active-text="是" 
          inactive-text="否" 
        />
      </el-form-item>
      
      <el-form-item 
        v-if="changePassword" 
        label="新密码" 
        prop="password"
      >
        <el-input 
          v-model="formData.password" 
          type="password" 
          show-password
          placeholder="请输入新密码"
        />
      </el-form-item>
    </template>
    
    <el-form-item>
      <el-button 
        type="primary" 
        @click="submitForm"
        :loading="loading"
      >
        {{ isCreate ? '创建' : '保存' }}
      </el-button>
      <el-button @click="resetFormFunc">重置</el-button>
    </el-form-item>
  </el-form>
</template>

<script setup lang="ts">
import { ref, reactive, watch, onUnmounted } from 'vue'
import type { FormInstance, UploadFile } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import type { User } from '@/api/modules/user'
import { updateUser, addUser } from '@/api/modules/user'
import { uploadFile } from '@/utils'

// 定义组件属性
const props = defineProps<{
  modelValue: Partial<User> | null
  isCreate?: boolean
}>()

// 定义事件
const emit = defineEmits<{
  (e: 'update:modelValue', value: Partial<User> | null): void
  (e: 'success', user: User): void
  (e: 'error', error: any): void
}>()

// 表单引用
const formRef = ref<FormInstance | null>(null)

// 加载状态
const loading = ref(false)

// 是否修改密码（仅在编辑模式下使用）
const changePassword = ref(false)

// 上传的文件ID
const avatarUploadId = ref<number | null>(null)

// 待上传的头像文件
const pendingAvatarFile = ref<File | null>(null)

// 预览头像URL
const previewAvatarUrl = ref<string | null>(null)

// 表单数据
const formData = reactive<Partial<User>>({
  user_id: undefined,
  account: '',
  password: '',
  name: '',
  signature: '',
  avatar: '',
  avatar_upload_id: null,
  role: undefined
})

// 重置表单函数（重命名为resetFormFunc以避免与resetForm变量冲突）
const resetFormFunc = () => {
  formRef.value?.resetFields()
  changePassword.value = false
  avatarUploadId.value = null
  pendingAvatarFile.value = null
  
  // 释放之前的预览URL
  if (previewAvatarUrl.value) {
    URL.revokeObjectURL(previewAvatarUrl.value)
    previewAvatarUrl.value = null
  }
  
  if (props.modelValue) {
    Object.assign(formData, props.modelValue)
    // 确保密码字段为空，避免显示之前输入的密码
    formData.password = ''
  } else {
    formData.user_id = undefined
    formData.account = ''
    formData.password = ''
    formData.name = ''
    formData.signature = ''
    formData.avatar = ''
    formData.avatar_upload_id = null
    formData.role = undefined
  }
}

// 添加一个专门用于清理密码的函数
const clearPassword = () => {
  formData.password = ''
  changePassword.value = false
}

// 清理预览头像URL
const clearPreviewAvatar = () => {
  if (previewAvatarUrl.value) {
    URL.revokeObjectURL(previewAvatarUrl.value)
    previewAvatarUrl.value = null
  }
}

// 监听传入的值变化
watch(
  () => props.modelValue,
  (newVal) => {
    if (newVal) {
      Object.assign(formData, newVal)
      // 当切换编辑的用户时，重置changePassword状态和密码字段
      clearPassword()
      // 清理之前的头像预览
      clearPreviewAvatar()
    } else {
      resetFormFunc()
    }
  },
  { immediate: true }
)

// 表单验证规则
const rules = reactive({
  account: [
    { required: true, message: '请输入账号', trigger: 'blur' },
    { min: 2, max: 20, message: '账号长度应在2-20个字符之间', trigger: 'blur' }
  ],
  name: [
    { required: true, message: '请输入姓名', trigger: 'blur' },
    { min: 2, max: 20, message: '姓名长度应在2-20个字符之间', trigger: 'blur' }
  ],
  password: [
    { required: props.isCreate || changePassword.value, message: '请输入密码', trigger: 'blur' },
    { min: 1, max: 20, message: '密码长度应在1-20个字符之间', trigger: 'blur' }
  ],
  signature: [
    { max: 200, message: '签名长度不能超过200个字符', trigger: 'blur' }
  ]
})

// 监听changePassword变化，动态更新密码字段的验证规则
watch(
  () => changePassword.value,
  (newVal) => {
    // 当在编辑模式下切换密码修改状态时，动态更新密码字段的required状态
    if (!props.isCreate) {
      rules.password[0].required = newVal
    }
  }
)

// 处理头像上传
const handleAvatarChange = async (file: UploadFile) => {
  // 简单的文件类型检查
  const isImage = file.raw?.type.startsWith('image/')
  const isLt2M = file.raw && file.raw.size / 1024 / 1024 < 2

  if (!isImage) {
    ElMessage.error('头像必须是图片格式!')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('头像大小不能超过 2MB!')
    return false
  }

  // 保存待上传的文件，但不立即上传
  pendingAvatarFile.value = file.raw!
  
  // 创建预览URL
  if (file.raw) {
    previewAvatarUrl.value = URL.createObjectURL(file.raw)
  }
  
  ElMessage.info('已选择新的头像文件，保存时将自动上传')
  return true
}

// 上传头像文件
const uploadPendingAvatar = async () => {
  if (!pendingAvatarFile.value) return true

  try {
    // 使用公共的上传方法上传头像
    const response = await uploadFile(pendingAvatarFile.value, {
      fileType: 'avatar'
    });
    
    if (response.code === 200) {
      // 存储上传文件的ID
      avatarUploadId.value = response.data.upload_id;
      pendingAvatarFile.value = null
      return true
    }
  } catch (error: any) {
    console.error('头像上传失败:', error);
    return false
  }
}

// 提交表单
const submitForm = async () => {
  if (!formRef.value) return

  try {
    // 先进行表单验证
    await formRef.value.validate()
    
    // 验证通过，继续执行提交逻辑
    loading.value = true
    
    try {
      // 如果有待上传的头像文件，先上传头像
      if (pendingAvatarFile.value) {
        const uploadSuccess = await uploadPendingAvatar()
        if (!uploadSuccess) {
          // 上传失败，停止提交
          loading.value = false
          return
        }
      }
      
      // 准备提交数据
      const submitData = { ...formData }
      
      // 如果是编辑模式且没有修改密码，则删除密码字段
      if (!props.isCreate && !changePassword.value) {
        delete submitData.password
      }
      
      // 如果有上传新的头像，则使用avatar_upload_id而不是avatar
      if (avatarUploadId.value) {
        submitData.avatar_upload_id = avatarUploadId.value;
        // 删除avatar字段，让后端根据avatar_upload_id设置avatar
        delete submitData.avatar;
      }
      
      let result: any;
      if (props.isCreate) {
        // 创建用户
        result = await addUser(submitData as any)
      } else {
        // 更新用户信息
        result = await updateUser(submitData)
      }
      
      ElMessage.success(result.msg)
      emit('success', result.data || submitData)
    } catch (error) {
      console.error('提交失败:', error)
      emit('error', error)
    } finally {
      loading.value = false
    }
  } catch (error) {
    // 表单验证失败，不需要特殊处理，Element Plus 会自动显示错误信息
    console.log('表单验证失败:', error)
  }
}

// 组件卸载时释放预览URL
onUnmounted(() => {
  if (previewAvatarUrl.value) {
    URL.revokeObjectURL(previewAvatarUrl.value)
  }
})
</script>

<style scoped>
.user-profile-form {
  max-width: 500px;
  margin: 0 auto;
}

.avatar-uploader .avatar {
  width: 120px;
  height: 120px;
  display: block;
  border-radius: 6px;
}

.avatar-uploader .avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 120px;
  height: 120px;
  text-align: center;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
}

.avatar-uploader .avatar-uploader-icon:hover {
  border-color: #409eff;
}

.pending-upload-info {
  margin-top: 10px;
}
</style>